from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import Dict, Any, List, Optional
from datetime import datetime
import json
import asyncio

from app.api import deps
from app.services.ai_manager import ai_service_manager
from app.services.ai_base import AIServiceProvider, AIServiceType, GenerationRequest
from app.core.config import settings

router = APIRouter()

@router.get("/debug/ai-services")
async def get_ai_service_debug_status():
    """获取所有AI服务的详细状态"""
    
    status = {}
    
    for provider, service in ai_service_manager.get_all_services().items():
        try:
            service_status = {
                "provider": provider.value,
                "available": True,
                "supported_services": [svc.value for svc in service.get_supported_services()],
                "config_status": _check_ai_service_config(service),
                "last_test_result": None
            }
        except Exception as e:
            service_status = {
                "provider": provider.value,
                "available": False,
                "error": str(e),
                "supported_services": [],
                "config_status": {},
                "last_test_result": None
            }
        
        status[provider.value] = service_status
    
    return {
        "ai_services": status,
        "total_services": len(status),
        "available_services": len([s for s in status.values() if s["available"]])
    }

@router.post("/debug/test-ai-service/{provider}")
async def test_ai_service_connection(
    provider: str,
    test_params: Dict[str, Any] = None,
    current_user = Depends(deps.get_current_user_optional)
):
    """测试AI服务连接"""
    
    try:
        ai_provider = AIServiceProvider(provider)
        service = ai_service_manager.get_service(ai_provider)
        
        if not service:
            raise HTTPException(status_code=404, detail=f"AI服务 {provider} 不存在")
        
        # 执行基本的服务测试
        test_results = {
            "provider": provider,
            "timestamp": datetime.now().isoformat(),
            "tests": []
        }
        
        # 测试1: 配置检查
        config_test = {
            "name": "配置检查",
            "status": "success",
            "details": _check_ai_service_config(service)
        }
        test_results["tests"].append(config_test)
        
        # 测试2: 支持的服务类型
        services_test = {
            "name": "支持的服务类型",
            "status": "success",
            "details": {
                "services": [svc.value for svc in service.get_supported_services()]
            }
        }
        test_results["tests"].append(services_test)
        
        # 测试3: 连接测试（如果是Google Veo 3）
        if provider == "google_veo3":
            connection_test = await _test_google_veo3_connection(service, test_params or {})
            test_results["tests"].append(connection_test)
        
        return test_results
        
    except ValueError:
        raise HTTPException(status_code=400, detail=f"不支持的AI服务提供商: {provider}")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"测试失败: {str(e)}")

@router.post("/debug/generate-test/{provider}")
async def test_ai_generation(
    provider: str,
    request_data: Dict[str, Any],
    current_user = Depends(deps.get_current_user_optional)
):
    """测试AI内容生成"""
    
    try:
        ai_provider = AIServiceProvider(provider)
        service = ai_service_manager.get_service(ai_provider)
        
        if not service:
            raise HTTPException(status_code=404, detail=f"AI服务 {provider} 不存在")
        
        # 构建生成请求
        generation_request = GenerationRequest(
            prompt=request_data.get("prompt", "测试提示词"),
            service_type=AIServiceType(request_data.get("service_type", "video_generation")),
            params=request_data.get("params", {}),
            user_id=current_user.id if current_user else 1
        )
        
        # 验证请求
        if not service.validate_request(generation_request):
            raise HTTPException(status_code=400, detail="请求参数验证失败")
        
        # 计算预估成本
        estimated_cost = service.calculate_cost(generation_request)
        
        # 根据服务类型调用对应方法
        if generation_request.service_type == AIServiceType.VIDEO_GENERATION:
            result = await service.generate_video(generation_request)
        elif generation_request.service_type == AIServiceType.IMAGE_GENERATION:
            result = await service.generate_image(generation_request)
        else:
            raise HTTPException(status_code=400, detail=f"不支持的服务类型: {generation_request.service_type}")
        
        return {
            "provider": provider,
            "service_type": generation_request.service_type.value,
            "request": {
                "prompt": generation_request.prompt,
                "params": generation_request.params
            },
            "estimated_cost": estimated_cost,
            "result": {
                "success": result.success,
                "result_url": result.result_url,
                "error_message": result.error_message,
                "metadata": result.metadata,
                "actual_cost": result.cost
            },
            "timestamp": datetime.now().isoformat()
        }
        
    except ValueError:
        raise HTTPException(status_code=400, detail=f"不支持的AI服务提供商: {provider}")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"生成测试失败: {str(e)}")

async def _test_google_veo3_connection(service, test_params: Dict[str, Any]) -> Dict[str, Any]:
    """测试Google Veo 3连接"""
    
    connection_test = {
        "name": "Google Veo 3连接测试",
        "status": "success",
        "details": {}
    }
    
    try:
        # 检查认证
        if hasattr(service, '_get_access_token'):
            try:
                token = await service._get_access_token()
                connection_test["details"]["authentication"] = {
                    "status": "success",
                    "has_token": bool(token),
                    "token_length": len(token) if token else 0
                }
            except Exception as e:
                connection_test["details"]["authentication"] = {
                    "status": "failed",
                    "error": str(e)
                }
                connection_test["status"] = "partial_failure"
        
        # 检查项目配置
        project_id = service.config.get("project_id")
        location = service.config.get("location")
        connection_test["details"]["project_config"] = {
            "project_id": project_id,
            "location": location,
            "has_project_id": bool(project_id),
            "has_location": bool(location)
        }
        
        # 检查API端点构建
        if hasattr(service, 'video_generation_url'):
            connection_test["details"]["api_endpoint"] = {
                "url": service.video_generation_url,
                "base_url": service.base_url
            }
        
        # 如果提供了测试参数，尝试构建请求
        if test_params.get("test_payload"):
            try:
                test_request = GenerationRequest(
                    prompt="测试连接",
                    service_type=AIServiceType.VIDEO_GENERATION,
                    params={"duration": 5, "resolution": "640x480"}
                )
                payload = service._build_video_generation_payload(test_request)
                connection_test["details"]["payload_generation"] = {
                    "status": "success",
                    "payload_keys": list(payload.keys())
                }
            except Exception as e:
                connection_test["details"]["payload_generation"] = {
                    "status": "failed",
                    "error": str(e)
                }
                connection_test["status"] = "partial_failure"
        
    except Exception as e:
        connection_test["status"] = "failed"
        connection_test["details"]["error"] = str(e)
    
    return connection_test

def _check_ai_service_config(service) -> Dict[str, Any]:
    """检查AI服务配置状态"""
    config_status = {}
    
    if hasattr(service, 'config'):
        config = service.config
        
        # 检查通用配置
        if hasattr(service, 'api_key'):
            api_key = getattr(service, 'api_key', None)
            config_status["api_key"] = {
                "configured": bool(api_key),
                "masked_value": f"***{api_key[-4:]}" if api_key and len(api_key) > 4 else None
            }
        
        # Google Veo 3特定配置
        if hasattr(service, 'project_id'):
            project_id = getattr(service, 'project_id', None)
            config_status["project_id"] = {
                "configured": bool(project_id),
                "value": project_id
            }
        
        if hasattr(service, 'location'):
            location = getattr(service, 'location', None)
            config_status["location"] = {
                "configured": bool(location),
                "value": location
            }
        
        if hasattr(service, 'max_duration'):
            max_duration = getattr(service, 'max_duration', None)
            config_status["max_duration"] = {
                "configured": bool(max_duration),
                "value": max_duration
            }
        
        # 服务账号配置
        service_account_path = config.get("service_account_path")
        if service_account_path:
            import os
            config_status["service_account"] = {
                "configured": bool(service_account_path),
                "file_exists": os.path.exists(service_account_path) if service_account_path else False,
                "path": service_account_path
            }
    
    return config_status

@router.get("/debug/ai-logs")
async def get_ai_service_logs(
    hours: int = Query(24, description="获取最近几小时的日志"),
    provider: Optional[str] = Query(None, description="AI服务提供商过滤"),
    service_type: Optional[str] = Query(None, description="服务类型过滤")
):
    """获取AI服务日志"""
    
    # 这里可以集成实际的日志系统
    # 目前返回模拟数据
    return {
        "logs": [
            {
                "timestamp": datetime.now().isoformat(),
                "provider": provider or "google_veo3",
                "service_type": service_type or "video_generation",
                "level": "INFO",
                "message": "AI服务调用成功",
                "details": {
                    "duration": "45.2s",
                    "cost": 0.85
                }
            }
        ],
        "filters": {
            "hours": hours,
            "provider": provider,
            "service_type": service_type
        }
    }